package com.yuejie.task;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;

import com.yuejie.bean.ResultPojo;
import com.yuejie.bean.SongPojo;
import com.yuejie.crawler.LyricCrawlerInTing;
import com.yuejie.resource.ResourceInTing;

public class StartLyricCrawlInTing implements Runnable {

	public ResourceInTing rr;
	public LyricCrawlerInTing h;
	public HttpClient hc;

	public StartLyricCrawlInTing(ResourceInTing rr, HttpClient hc) {
		this.hc = hc;
		this.rr = rr;
		this.h = new LyricCrawlerInTing(hc);
	}

	public static void main(String[] args) {

		ResourceInTing rr = new ResourceInTing();
		
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
		
//		HttpClient hc = new DefaultHttpClient(cm);
//		HttpClient hc2 = new DefaultHttpClient(cm);
		HttpClient hc_direct = new DefaultHttpClient(cm);//直连
		
//		设置代理
//		HttpHost proxy = new HttpHost("127.0.0.1", 8087);
//		hc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		
//		设置代理
//		HttpHost proxy2 = new HttpHost("173.242.123.178", 80);
//		hc2.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy2);

//		for (int i = 0; i < 15; i++) {
//			Thread r = new Test(rr, hc);
//			r.start();
//		}
		
//		for (int i = 0; i < 8; i++) {
//			Thread r = new Test(rr, hc2);
//			r.start();
//		}
		ExecutorService e = Executors.newCachedThreadPool();
		for (int i = 0; i < 40; i++) {
			Runnable r = new StartLyricCrawlInTing(rr, hc_direct);
			e.execute(r);
		}
	}

	@Override
	public void run() {
		while (rr.hasNext()) {
			SongPojo s = rr.next();
			ResultPojo result = h.getLyric(s);
			rr.write(s.getId(), result);
		}
	}
}
